//通用功能

const FileUpload = require('../common/FileUpload');
const base = require('./controller');

module.exports = class extends base {
    /**
     * 上传一个文件公用接口
     * @returns {*}
     */
    uploadimgAction() {

        let upFileObj = this.ctx.file();
        let fileArr = [];
        for (let item in upFileObj) {
            fileArr.push(upFileObj[item]);
        }
        if (fileArr.length <= 0) {
            return this.resErrmsg('没有选择上传文件')
        }
        if (fileArr.length > 1) {
            return this.resErrmsg('只能上传一个文件')
        }


        let savePath = think.ROOT_PATH + '/uploads/imgs/';
        if (!think.isDirectory(savePath)) think.mkdir(savePath);
        let fileObj = new FileUpload(fileArr[0], savePath);
        let fileInfo = fileObj.save();

        if (think.isEmpty(fileInfo)) {
            return this.resErrmsg('移动上传文件失败');
        } else {
            return this.resSuccessWithData(fileInfo);
        }
    }


    /**
     * 上传一个文件公用接口
     * @returns {*}
     */
    edituploadimgAction() {

        let upFileObj = this.ctx.file();
        let fileArr = [];
        for (let item in upFileObj) {
            fileArr.push(upFileObj[item]);
        }
        if (fileArr.length <= 0) {
            return this.resErrmsg('没有选择上传文件')
        }
        if (fileArr.length > 1) {
            return this.resErrmsg('只能上传一个文件')
        }


        let savePath = think.ROOT_PATH + '/uploads/imgs/';
        if (!think.isDirectory(savePath)) think.mkdir(savePath);
        let fileObj = new FileUpload(fileArr[0], savePath);
        let fileInfo = fileObj.save();

        if (think.isEmpty(fileInfo)) {
            return this.resErrmsg('移动上传文件失败');
        } else {
            return this.body=this.ctx.origin+fileInfo.saveFile;
        }
    }
};